/**
 * 
 */
package com.xunchi.haichuan.data.service;

import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

import com.xunchi.haichuan.configurator.model.SystemConfigs;
import com.xunchi.haichuan.data.dao.DataDAO;
import com.xunchi.haichuan.data.dao.DataDAOImpl;
import com.xunchi.haichuan.data.model.Data;
import com.xunchi.haichuan.utility.Constants;
import com.xunchi.haichuan.utility.MiscUtil;

/**
 * 作者：kongxb<br>
 * 模块名称：数据管理模块<br>
 * 功能描述：数据服务实现<br>
 * 维护记录：2009.11.27, kongxb 创建该类
 */
public class DataServiceImpl implements DataService {

    private DataDAO dataDAO;

    private int totalCount;

    private String SAVE_PATH = SystemConfigs.filePath;

    private final String[] EXCEL_TITLE = new String[] { "单位名称", "负责人", "联系人", "电话", "传真", "移动电话", "电子邮件", "网址", "地址",
            "邮政编码", "人员规模", "营业执照", "注册资金", "成立日期 ", "行业类型", "企业性质", "经营模式", "业务区域", "客户类别", "电话区号", "省", "市", "经营范围",
            "公司简介", "法人", "客户来源", "来源网页", "国家", "有效性" };

    /**
     * 构造函数
     */
    public DataServiceImpl() {
        dataDAO = new DataDAOImpl(Data.class);
    }

    /**
     * @see com.xunchi.haichuan.data.service.DataService#getLatestDatas(int, int)
     */
    public List<Data> getLatestDatas(int start, int limit) throws Exception {
        List<Data> dataList = dataDAO.getLatestDatas(start, limit);

        totalCount = dataList.size();
        return dataList;
    }

    /**
     * @see com.xunchi.haichuan.data.service.DataService#search(java.lang.String, java.lang.String, int, java.util.Date,
     *      java.util.Date)
     */
    public List<Data> search(String province, String city, int validation, Date beginDate, Date endDate)
            throws Exception {
        Data instance = new Data();
        instance.setProvince(province);
        instance.setCity(city);
        instance.setValidation(validation);

        List<Data> dataList = dataDAO.search(instance, beginDate, endDate);

        totalCount = dataList.size();
        sortDataList(dataList); // 按照提交时间逆序排序
        return dataList;
    }

    /**
     * @see com.xunchi.haichuan.data.service.DataService#search(java.lang.String, java.lang.String, int, java.util.Date,
     *      java.util.Date, int)
     */
    public List<Data> search(String province, String city, int validation, Date beginDate, Date endDate, int count)
            throws Exception {
        Data instance = new Data();
        instance.setProvince(province);
        instance.setCity(city);
        instance.setValidation(validation);

        List<Data> dataList = dataDAO.search(instance, beginDate, endDate, 0, count);

        totalCount = dataList.size();
        sortDataList(dataList); // 按照提交时间逆序排序
        return dataList;
    }

    /**
     * @see com.xunchi.haichuan.data.service.DataService#search(java.lang.String, java.lang.String, int, java.util.Date,
     *      java.util.Date, int, int)
     */
    public List<Data> search(String province, String city, int validation, Date beginDate, Date endDate, int start,
            int limit) throws Exception {
        List<Data> dataList = search(province, city, validation, beginDate, endDate);
        sortDataList(dataList); // 按照提交时间逆序排序
        return Arrays.asList((Data[]) ArrayUtils.subarray(dataList.toArray(new Data[] {}), start, start + limit));
    }

    /**
     * @see com.xunchi.haichuan.data.service.DataService#search(java.lang.String, java.lang.String, int, java.util.Date,
     *      java.util.Date, int, int, int)
     */
    public List<Data> search(String province, String city, int validation, Date beginDate, Date endDate, int count,
            int start, int limit) throws Exception {
        List<Data> dataList = search(province, city, validation, beginDate, endDate, count);
        sortDataList(dataList); // 按照提交时间逆序排序
        return Arrays.asList((Data[]) ArrayUtils.subarray(dataList.toArray(new Data[] {}), start, start + limit));
    }

    /**
     * @see com.xunchi.haichuan.data.service.DataService#getTotalCount()
     */
    public int getTotalCount() {
        return this.totalCount;
    }

    /**
     * @see com.xunchi.haichuan.data.service.DataService#getDataById(java.lang.String)
     */
    public Data getDataById(String dataId) throws Exception {
        return dataDAO.getByID(dataId);
    }

    /**
     * @see com.xunchi.haichuan.data.service.DataService#sortDataList(java.util.List<Data>)
     */
    public void sortDataList(List<Data> dataList) {
        // 按照提交时间逆序排序
        Collections.sort(dataList, Collections.reverseOrder(new Comparator() {
            public int compare(Object o1, Object o2) {
                Data f1 = (Data) o1;
                Data f2 = (Data) o2;
                return (f1.getSubmitTime().compareTo(f2.getSubmitTime()));
            }
        }));
    }

    /**
     * @see com.xunchi.haichuan.data.service.DataService#importFromExcelFile(java.util.List<Data>)
     */
    public boolean importFromExcelFile(File file) throws Exception {
        // 创建只读的Excel工作薄
        jxl.Workbook rwb = jxl.Workbook.getWorkbook(file);
        // 获取第一张Excel工作表
        jxl.Sheet rs = rwb.getSheet(0);

        // 获取列数
        int columnCount = rs.getColumns();
        // 获取行数
        int rowCount = rs.getRows();

        // 获取第一行的值
        jxl.Cell[] cells = rs.getRow(0);
        String[] titles = new String[columnCount];
        for (int i = 0; i < cells.length; i++) {
            titles[i] = cells[i].getContents();
            System.out.print(cells[i].getContents());
            System.out.print(" ");
        }
        System.out.print("\n");

        int[] index = new int[EXCEL_TITLE.length];
        for (int i = 0; i < index.length; i++) {
            index[i] = -1;
            index[i] = ArrayUtils.indexOf(titles, EXCEL_TITLE[i]);
        }

        if (index[0] == -1) { // 单位名称必须存在
            return false;
        }

        String[] record = new String[EXCEL_TITLE.length];
        Data data;
        for (int i = 1; i < rowCount; i++) {
            cells = rs.getRow(i);
            for (int j = 0; j < EXCEL_TITLE.length; j++) {
                if (index[j] == -1) {
                    record[j] = null;
                } else {
                    record[j] = cells[index[j]].getContents();
                }
            }

            String dataName = record[0];
            if (StringUtils.isBlank(dataName)) { // // 如果单位名称为空，则跳过
                continue;
            }
            if (dataDAO.checkDataName(dataName)) { // 检查这条数据是否存在
                continue;
            }

            data = new Data();
            data.setName(dataName);
            data.setPersonInCharge(record[1]);
            data.setContact(record[2]);
            data.setTel(record[3]);
            data.setFax(record[4]);
            data.setMobile(record[5]);
            data.setEmail(record[6]);
            data.setWebsite(record[7]);
            data.setAddress(record[8]);
            data.setPostcode(record[9]);
            data.setStaffSize(record[10]);
            data.setLicense(record[11]);
            data.setRegisteredCapital(record[12]);
            data.setEstablishDate(record[13]);
            data.setIndustryType(record[14]);
            data.setEnterpriseNature(record[15]);
            data.setBusinessModel(record[16]);
            data.setBusinessArea(record[17]);
            data.setCustomerType(record[18]);
            data.setTelCode(record[19]);
            data.setProvince(record[20]);
            data.setCity(record[21]);
            data.setBusinessScope(record[22]);
            data.setBrief(record[23]);
            data.setLegal(record[24]);
            data.setCustomerSource(record[25]);
            data.setSourceUrl(record[26]);
            data.setCountry(record[27]);
            if (record[10] != null) {
                try {
                    data.setValidation(Integer.parseInt(record[28]));
                } catch (NumberFormatException ex) {
                    data.setValidation(-1);
                }
            } else {
                data.setValidation(-1);
            }
            dataDAO.saveEntity(data);
        }

        // 关闭Excel工作薄对象
        rwb.close();

        return true;
    }

    /**
     * @see com.xunchi.haichuan.data.service.DataService#exportToExcelFile(java.util.List<Data>)
     */
    public File exportToExcelFile(List<Data> dataList) throws Exception {
        String fileName = MiscUtil.getRandomName() + Constants.FILE_EXT_EXCEL;
        File file = new File(SAVE_PATH.concat(fileName));

        // 创建可写入的Excel工作薄
        jxl.write.WritableWorkbook wwb = jxl.Workbook.createWorkbook(file);
        // 创建Excel工作表
        jxl.write.WritableSheet ws = wwb.createSheet("Sheet1", 0);

        ws.setColumnView(0, 60);
        ws.setColumnView(1, 20);
        ws.setColumnView(2, 20);
        ws.setColumnView(3, 30);
        ws.setColumnView(4, 30);
        ws.setColumnView(5, 30);
        ws.setColumnView(6, 40);
        ws.setColumnView(7, 40);
        ws.setColumnView(8, 60);
        ws.setColumnView(9, 20);
        ws.setColumnView(10, 20);
        ws.setColumnView(11, 30);
        ws.setColumnView(12, 20);
        ws.setColumnView(13, 30);
        ws.setColumnView(14, 20);
        ws.setColumnView(15, 20);
        ws.setColumnView(16, 30);
        ws.setColumnView(17, 30);
        ws.setColumnView(18, 30);
        ws.setColumnView(19, 20);
        ws.setColumnView(20, 20);
        ws.setColumnView(21, 20);
        ws.setColumnView(22, 40);
        ws.setColumnView(23, 80);
        ws.setColumnView(24, 20);
        ws.setColumnView(25, 40);
        ws.setColumnView(26, 40);
        ws.setColumnView(27, 20);

        jxl.write.WritableFont wf = new jxl.write.WritableFont(jxl.write.WritableFont.TIMES, 12,
                jxl.write.WritableFont.BOLD);
        jxl.write.WritableCellFormat wcf = new jxl.write.WritableCellFormat(wf);
        wcf.setBackground(jxl.format.Colour.CORAL);

        jxl.write.Label label;
        for (int i = 0; i < EXCEL_TITLE.length - 1; i++) {
            label = new jxl.write.Label(i, 0, EXCEL_TITLE[i], wcf);
            ws.addCell(label);
        }

        int i = 1;
        Data data;
        for (Iterator iter = dataList.iterator(); iter.hasNext();) {
            data = (Data) iter.next();

            label = new jxl.write.Label(0, i, data.getName());
            ws.addCell(label);
            label = new jxl.write.Label(1, i, data.getPersonInCharge());
            ws.addCell(label);
            label = new jxl.write.Label(2, i, data.getContact());
            ws.addCell(label);
            label = new jxl.write.Label(3, i, data.getTel());
            ws.addCell(label);
            label = new jxl.write.Label(4, i, data.getFax());
            ws.addCell(label);
            label = new jxl.write.Label(5, i, data.getMobile());
            ws.addCell(label);
            label = new jxl.write.Label(6, i, data.getEmail());
            ws.addCell(label);
            label = new jxl.write.Label(7, i, data.getWebsite());
            ws.addCell(label);
            label = new jxl.write.Label(8, i, data.getAddress());
            ws.addCell(label);
            label = new jxl.write.Label(9, i, data.getPostcode());
            ws.addCell(label);
            label = new jxl.write.Label(10, i, data.getStaffSize());
            ws.addCell(label);
            label = new jxl.write.Label(11, i, data.getLicense());
            ws.addCell(label);
            label = new jxl.write.Label(12, i, data.getRegisteredCapital());
            ws.addCell(label);
            label = new jxl.write.Label(13, i, data.getEstablishDate());
            ws.addCell(label);
            label = new jxl.write.Label(14, i, data.getIndustryType());
            ws.addCell(label);
            label = new jxl.write.Label(15, i, data.getEnterpriseNature());
            ws.addCell(label);
            label = new jxl.write.Label(16, i, data.getBusinessModel());
            ws.addCell(label);
            label = new jxl.write.Label(17, i, data.getBusinessArea());
            ws.addCell(label);
            label = new jxl.write.Label(18, i, data.getCustomerType());
            ws.addCell(label);
            label = new jxl.write.Label(19, i, data.getTelCode());
            ws.addCell(label);
            label = new jxl.write.Label(20, i, data.getProvince());
            ws.addCell(label);
            label = new jxl.write.Label(21, i, data.getCity());
            ws.addCell(label);
            label = new jxl.write.Label(22, i, data.getBusinessScope());
            ws.addCell(label);
            label = new jxl.write.Label(23, i, data.getBrief());
            ws.addCell(label);
            label = new jxl.write.Label(24, i, data.getLegal());
            ws.addCell(label);
            label = new jxl.write.Label(25, i, data.getCustomerSource());
            ws.addCell(label);
            label = new jxl.write.Label(26, i, data.getSourceUrl());
            ws.addCell(label);
            label = new jxl.write.Label(27, i, data.getCountry());
            ws.addCell(label);

            i++;
        }

        // 写入Excel工作表
        wwb.write();
        // 关闭Excel工作薄对象
        wwb.close();

        return file;
    }

}
